package com.dixon.worddayday.service;

import com.dixon.worddayday.config.BusinessException;
import com.dixon.worddayday.model.Words;
import com.dixon.worddayday.util.ICrawler;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class WordCrawler implements ICrawler<Words> {

    private static String CRAW_URL = "http://kkdict.com/en/";

    /**
     * @param word http://kkdict.com/en/mother
     * @return
     */
    @Override
    public Words craw(String word) {
        String url = CRAW_URL + word.trim();

        Words result = null;
        try {
            // 使用Jsoup连接目标网页
            Document document = Jsoup.connect(url).get();
            String wordShow = document.selectFirst(".titWord").children().first().text();
//            String word = document.selectXpath("/html/body/div[5]/div[1]/div[1]/div/h1").text();
            if(!StringUtils.isEmpty(wordShow)) {
                // 声音链接
                String voiceUrl = document.selectXpath("/html/body/div[3]/div[1]/div[1]/div/div[1]/a").attr("onclick");
                voiceUrl = voiceUrl.replace("asplay_h5('","").replace("');return false;", "");
                // 解释
                String paraphrase = document.getElementById("wordm").text();
                // 例句
                String example = document.getElementById("s_ul").text();

                result = new Words(word.trim(), wordShow.trim(), voiceUrl, paraphrase, example);
            }

        } catch (Exception e) {
            throw new BusinessException("获取单词失败");
        }

        return result;
    }

    public static void main(String[] args) {
        String word = "mother";  // 网页的url

        ICrawler<Words> crawler = new WordCrawler();
        Words result = crawler.craw(word);

        System.out.println(result);
    }
}